package com.open.capacity.service.impl;

import com.open.capacity.config.SendMessage;
import com.open.capacity.dao.MessageDao;
import com.open.capacity.model.MessageModel;
import com.open.capacity.redis.util.RedisUtil;
import com.open.capacity.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: y_022
 * @date: 11:08-2021/7/19
 * @description:
 */
@Service
public class MessageServiceImpl implements MessageService {
    private static final String KEY_PRE_MESSAGE = "KEY_PRE_MESSAGE"; //缓存中的新下单消息的前缀
    private static final String KEY_PRE_MESSAGE_COUNT = "KEY_PRE_MESSAGE_COUNT"; //缓存中的消息的总数前缀
    private static final String QUEUE = "QUEUE"; //路由键前缀
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SendMessage sendMessage;

    /**
     * 从数据库中查询支付成功后的消息
     *
     * @param messageModel
     * @return
     */
    @Override
    public String getMessage(MessageModel messageModel) {
        return sendMessage.GetMessage(QUEUE + messageModel.getUserid());
    }
    /**
     * 从缓存中查询消息总数
     *
     * @param messageModel
     * @return
     */
    @Override
    public Integer getMessageCount(MessageModel messageModel) {
        Integer count = 0;
        String key = KEY_PRE_MESSAGE_COUNT + messageModel.getUserid();
        if (redisUtil.hasKey(key)) {
            count = (Integer) redisTemplate.opsForValue().get(key);
        }
        return count;
    }

    @Override
    public void deleteMessage(MessageModel messageModel) {
        Integer count = 0;
        String key = KEY_PRE_MESSAGE_COUNT + messageModel.getUserid();
        if (!redisUtil.hasKey(key)) {
            //从缓存中检测保存消息的key是否存在，先取出，然后最后在重新set，达到更新的目的。
            count = (Integer) redisTemplate.opsForValue().get(key);
            redisTemplate.opsForValue().set(key, --count, 86400, TimeUnit.SECONDS);
        }
        redisTemplate.opsForValue().decrement(key);
        messageDao.deleteMessage(messageModel);
    }
}
